<script lang="ts" setup>
import { reactive, ref, watch, type ComponentPublicInstance, nextTick, computed } from "vue"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import {
  Search,
  Refresh,
  CirclePlus,
  RefreshRight,
  Tickets,
  Download,
  Delete,
  UploadFilled
} from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import Warehouse from "./components/dialog.vue"
import price from "./components/price.vue"
//批量入库
import batch from "./components/batch.vue"
import getDetails from "./components/details.vue"
import UploadDialog from "./components/UploadDialog.vue"
import Create from "./components/create.vue"
import edit from "./components/edit.vue"
import uploadLog from "../components/uploadLog/index.vue"
import batchEdit from "./components/batchEdit.vue"
import { doCreateApi, doDeleteApi, batchDeleteApi } from "@/api/bill"
import {
  getBillExportApi,
  getBillListApi,
  getIndexApi,
  getCountApi,
  doEditBillBackUserApi,
  doCancelApi,
  getPendingCompaniesApi
} from "@/api/billv2"
import dayjs from "dayjs"
import { getAdminRoleListApi } from "@/api/system"
import { frontExport, sumValuesForName, copyToClipboard } from "@/utils/common"
import Decimal from "decimal.js"
import face from "@/views/bill/components/faceCatch/index.vue"
import { dictDataGetListApi } from "@/api/conventional"
import History from "./components/history.vue"
import Checkout from "./components/checkout.vue"
import ImageRecognitionUploader from "./components/ImageRecognitionUploader.vue"
import ImageRecognitionImporter from "./components/ImageRecognitionImporter.vue"
import Retreat from "./components/retreat/Retreat.vue"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})
const addCompany = () => {
  if (priceRef.value) {
    priceRef.value.show()
  }
}
const addCompany2 = (row: any) => {
  if (priceRef.value) {
    priceRef.value.show2(row)
  }
}
// const uploadLogShow = () => {
//   if (uploadLogRef.value) {
//     uploadLogRef.value.uploadShow()
//   }
// }

const height = ref<number>(200)
const loading = ref<boolean>(false)
const countBool = ref<boolean>(false)
const faceRef = ref<any>(null)
const uploadLogRef = ref<any>(null)
const dialogRef = ref<any>(null)
const createRef = ref<any>(null)
const editRef = ref<any>(null)
const batchRef = ref<any>(null)
const priceRef = ref<any>()
const UploadDialogRef = ref<any>(null)
const ImageRecognitionUploaderRef = ref<any>(null)
const ImageRecognitionImporterRef = ref<any>(null)
const CatchListDialogRef = ref<any>(null)
const detailsRef = ref<any>(null)
const batchEditRef = ref<any>(null)
const checkoutRef = ref<any>(null)
const listboxLeftRef = ref<any>(null)
const customDateFormat = ref<string>("YYYY-MM-DD")
const customDateTimeFormat = ref<string>("YYYY-MM-DD HH:mm:ss")
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const HistoryRef = ref<ComponentPublicInstance<InstanceType<typeof History>> | null>(null)

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  billAmount: "",
  billNo: "",
  bill_type: 1,
  expirationDate: "",
  acceptorName: "",
  bill_back_user: ""
})
const formRules: FormRules = reactive({
  billNo: [
    { required: true, trigger: "blur", message: "请输入票号" },
    { min: 30, max: 30, message: "长度为30个字符", trigger: "blur" }
  ],
  billAmount: [{ required: true, trigger: "blur", message: "请输入金额" }],
  bill_type: [{ required: true, trigger: "blur", message: "请选择票据类型" }],
  expirationDate: [{ required: true, type: "date", trigger: "change", message: "请选择到期日" }],
  acceptorName: [{ required: true, trigger: "blur", message: "请输入承兑人" }],
  bill_back_user: [{ required: true, trigger: "blur", message: "请输入背书人" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      doCreateApi({
        billAmount: parseFloat(formData.billAmount),
        billNo: formData.billNo,
        bill_type: formData.bill_type,
        expirationDate: formData.expirationDate,
        acceptorName: formData.acceptorName,
        bill_back_user: formData.bill_back_user
      })
        .then(() => {
          ElMessage.success("新增成功")
          console.log("sadas", searchData)
          getTableData()
        })
        .finally(() => {
          dialogVisible.value = false
        })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  formData.billAmount = ""
  formData.billNo = ""
  formData.bill_type = 1
  formData.expirationDate = ""
  formData.acceptorName = ""
  formData.bill_back_user = ""
  searchData.buttonType = "pending"
  searchData.acceptorName = ""
  searchData.bill_back_user = ""
  searchData.billAmountMin = ""
  searchData.billAmountMax = ""
  searchData.expirationDateStart = ""
  searchData.expirationDateEnd = ""
  searchData.enter_timeStart = ""
  searchData.enter_timeEnd = ""
  searchData.date1 = ""
  searchData.date2 = ""
  searchData.uid = undefined
}
//#endregion

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.prompt("请输入删除原因", `正在删除票据：${row.billNo}，确认删除？`, {
    confirmButtonText: "确认",
    cancelButtonText: "取消"
  })
    .then(({ value }) => {
      doDeleteApi({
        bill_id: row.bill_id,
        reason: value
      }).then(() => {
        ElMessage.success("删除成功")
        getTableData()
      })
    })
    .catch(() => {})
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
// const handleUpdate = (row: GetTableData) => {
//   dialogRef.value.dialogShow()
//   // currentUpdateId.value = row.id
//   // formData.username = row.username
//   // dialogVisible.value = true
// }
const handleUpdate = (row: any) => {
  if (dialogRef.value) {
    dialogRef.value?.dialogShow(row)
  }
}
const handleEdits = (row: any) => {
  if (editRef.value) {
    editRef.value?.dialogShow(row)
  }
}
//#endregion

//#region 查
const currentDate = dayjs()

const tableData = ref<any[]>([])
const listData = ref<any>([])
const tableLoading = ref<boolean>(false)
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  billNo: "",
  buttonType: "pending",
  acceptorName: "",
  bill_back_user: "",
  billAmountMin: "",
  billAmountMax: "",
  expirationDateStart: "",
  expirationDateEnd: "",
  enter_timeStart: currentDate.format("YYYY-MM-DD 00:00:00"),
  enter_timeEnd: currentDate.add(1, "day").format("YYYY-MM-DD 00:00:00"),
  uid: undefined,
  company_type: undefined,
  date1: "",
  date2: "",
  invoicing_type: undefined,
  check_type: undefined
})
const options = [
  {
    value: 1,
    label: "客户"
  },
  {
    value: 2,
    label: "平台"
  },
  {
    value: 3,
    label: "中介"
  },
  {
    value: 4,
    label: "银行"
  }
]
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}
getAdminList()
const pendingCompaniesData = ref<any[]>([])
const companySearchKeyword = ref<string>("")
const filteredPendingCompanies = computed(() => {
  if (!companySearchKeyword.value) return pendingCompaniesData.value
  return pendingCompaniesData.value.filter((company) =>
    company.company_name.toLowerCase().includes(companySearchKeyword.value.toLowerCase())
  )
})
const getPendingCompanies = async () => {
  const res: any = await getPendingCompaniesApi({
    buttonType: searchData.buttonType || "all"
  })
  pendingCompaniesData.value = res.data.list
}
getPendingCompanies()
const getTableData = () => {
  height.value = 100
  loading.value = true
  tableLoading.value = true
  getBillListApi({
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    acceptorName: searchData.acceptorName || undefined,
    bill_back_user: searchData.bill_back_user || undefined,
    billAmountMin: searchData.billAmountMin || undefined,
    billAmountMax: searchData.billAmountMax || undefined,
    billNo: searchData.billNo || undefined,
    date1: searchData.date1 || undefined,
    date2: searchData.date2 || undefined,
    enter_timeStart: searchData.enter_timeStart || undefined,
    enter_timeEnd: searchData.enter_timeEnd || undefined,
    company_type: searchData.company_type || undefined,
    invoicing_type: searchData.invoicing_type || undefined,
    check_type: searchData.check_type || undefined,
    uid: searchData.uid || undefined,
    pageType: "received",
    buttonType: searchData.buttonType || "all"
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
      getIndexData()
      getCountData()
      getPendingCompanies()
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
      tableLoading.value = false
      // 等待 DOM 更新完成后再获取最新的高度
      nextTick(() => {
        height.value = listboxLeftRef.value.clientHeight
      })
    })
}
const getIndexData = () => {
  getIndexApi({
    pageType: "received",
    buttonType: searchData.buttonType || "all",
    enter_timeStart: searchData.enter_timeStart || undefined,
    enter_timeEnd: searchData.enter_timeEnd || undefined
  })
    .then((res: any) => {
      const inputValues = res.data
      buttonList.forEach((button: any) => {
        const inputValue = inputValues[button.name]
        button.badge = ""
        if (inputValue !== undefined && inputValue != 0) {
          button.badge = inputValue
        }
      })
    })
    .catch(() => {})
    .finally(() => {})
}
const getCountData = async () => {
  resetCountData()
  const res: any = await getCountApi({
    pageType: "received",
    buttonType: searchData.buttonType || "all",
    billNo: searchData.billNo || undefined,
    date1: searchData.date1 || undefined,
    date2: searchData.date2 || undefined,
    acceptorName: searchData.acceptorName || undefined,
    bill_back_user: searchData.bill_back_user || undefined,
    billAmountMin: searchData.billAmountMin || undefined,
    billAmountMax: searchData.billAmountMax || undefined,
    uid: searchData.uid || undefined,
    company_type: searchData.company_type || undefined,
    invoicing_type: searchData.invoicing_type || undefined,
    check_type: searchData.check_type || undefined,
    enter_timeStart: searchData.enter_timeStart || undefined,
    enter_timeEnd: searchData.enter_timeEnd || undefined
  })

  countData.enter_count = res.data.count
  countData.enter_amount = res.data.amount
  if (res.data.complete) {
    countData.enter_complete = res.data.complete
  } else {
    countData.enter_complete = 0
  }
  if (res.data.discount) {
    countData.enter_discount = res.data.discount
  } else {
    countData.enter_discount = 0
  }
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchData.acceptorName = ""
  searchData.bill_back_user = ""
  searchData.billAmountMin = ""
  searchData.billAmountMax = ""
  searchData.expirationDateStart = ""
  searchData.expirationDateEnd = ""
  searchData.enter_timeStart = currentDate.format("YYYY-MM-DD 00:00:00")
  searchData.enter_timeEnd = currentDate.add(1, "day").format("YYYY-MM-DD 00:00:00")
  searchData.billNo = ""
  searchData.date1 = ""
  searchData.date2 = ""
  searchData.uid = undefined
  searchData.company_type = undefined
  searchData.invoicing_type = undefined
  searchData.check_type = undefined
  searchFormRef.value?.resetFields()
  handleSearch()
}
const handBatchDialog = () => {
  if (Object.keys(lists).length === 0) {
    ElMessage.warning("请选择需要操作的票据")
    return
  }

  if (batchRef.value) {
    batchRef.value?.batchShow(lists)
  }
}
let lists = reactive({})
const handleSelectionChange = (val: any) => {
  if (val.length === 0) {
    resetSelectedCountData()
    countBool.value = false
  } else {
    selectedCountData.count = val.length
    selectedCountData.amount = sumValuesForName(val, "billAmount")
    if (searchData.buttonType == "complete") {
      selectedCountData.complete = sumValuesForName(val, "enter_finally")
      selectedCountData.complete = parseFloat(selectedCountData.complete.toFixed(2))
      selectedCountData.discount = sumValuesForName(val, "enter_discount")
      selectedCountData.discount = parseFloat(selectedCountData.discount.toFixed(2))
    }
    countBool.value = true
  }
  selectedRows.value = val
  lists = {}
  Object.assign(lists, {}, val)
}
const selectedRows = ref<any[]>([])
const rowStyle = ({ rowIndex }: { rowIndex: number }) => {
  // 检查当前行是否在选中行中
  return selectedRows.value.includes(tableData.value[rowIndex]) ? { background: "#E6A23C !important" } : {}
}

const modality = (row: any) => {
  // if (row.columnIndex == 2) {
  //   return {
  //     color: "#2e90f7",
  //     border: "1px solid #cccccc"
  //   }
  // }
  if (row.columnIndex == 4) {
    return {
      color: "red",
      border: "1px solid #cccccc"
    }
  }
  return {
    border: "1px solid #cccccc"
  }
}

const getBillExport2 = () => {
  console.log(selectedRows.value)
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要导出的数据")
    return
  }
  const header = [
    "入库时间",
    "票号",
    "承兑人",
    "票面金额（万）",
    "",
    "到期日",
    "入库每十万价格",
    "入库贴息费",
    "入库实付金额",
    "",
    "背书人",
    "出库客户",
    "出库每十万价格",
    "出库贴息费",
    "出库实收金额",
    "差额",
    "出库时间",
    "入库业务员",
    "出库业务员"
  ]
  const data = selectedRows.value.map((item: any) => [
    item.enter_time,
    item.billNo,
    item.acceptorName,
    item.billAmount,
    "",
    item.expirationDate,
    new Decimal(item.enter_price || 0).div(new Decimal(1000)) + "%",
    item.enter_discount,
    item.enter_finally,
    "",
    item.bill_back_user,
    item.out_state,
    new Decimal(item.out_price || 0).div(new Decimal(1000)) + "%",
    item.out_discount,
    item.out_finally,
    item.profit,
    item.out_time,
    item.enter_nickname,
    item.out_nickname
  ])
  frontExport(data, header)
}

const getBillExport = () => {
  loading.value = true
  getBillExportApi({
    pageType: "received",
    buttonType: searchData.buttonType || "all",
    billNo: searchData.billNo || undefined,
    date1: searchData.date1 || undefined,
    date2: searchData.date2 || undefined,
    acceptorName: searchData.acceptorName || undefined,
    bill_back_user: searchData.bill_back_user || undefined,
    billAmountMin: searchData.billAmountMin || undefined,
    billAmountMax: searchData.billAmountMax || undefined,
    enter_timeStart: searchData.enter_timeStart || undefined,
    enter_timeEnd: searchData.enter_timeEnd || undefined,
    history_type: undefined,
    uid: searchData.uid || undefined,
    churu_type: undefined
  })
    .then((res: any) => {
      links(res.data.filePath)
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
}
const links = (filePath: string) => {
  const link = document.createElement("a") // 创建一个 a 标签用来模拟点击事件
  link.style.display = "none"
  link.href = filePath
  link.setAttribute("download", "票据管理")
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
//#endregion

const selectedCountData = reactive({
  count: 0,
  amount: 0,
  complete: 0,
  discount: 0
})
const resetSelectedCountData = () => {
  selectedCountData.count = 0
  selectedCountData.amount = 0
  selectedCountData.complete = 0
  selectedCountData.discount = 0
}
const countData = reactive({
  enter_count: 0,
  enter_amount: 0,
  enter_complete: 0,
  enter_discount: 0
})
const resetCountData = () => {
  countData.enter_count = 0
  countData.enter_amount = 0
  countData.enter_complete = 0
  countData.enter_discount = 0
}
const resetEnterTime = () => {
  if (searchData.buttonType == "incomplete") {
    searchData.enter_timeStart = ""
    searchData.enter_timeEnd = ""
  } else {
    if (searchData.enter_timeStart == "") {
      searchData.enter_timeStart = currentDate.format("YYYY-MM-DD 00:00:00")
    }
    if (searchData.enter_timeEnd == "") {
      searchData.enter_timeEnd = currentDate.add(1, "day").format("YYYY-MM-DD 00:00:00")
    }
  }
}
const buttonList = reactive<any>([
  { name: "all", label: "全部订单", badge: "" },
  { name: "pending", label: "待入库信息", badge: "" },
  { name: "incomplete", label: "入库未完成", badge: "" },
  { name: "complete", label: "入库完成", badge: "" },
  { name: "failed", label: "失败的订单", badge: "" }
])
const buttonStates = reactive<any>({
  all: false,
  pending: true,
  incomplete: false,
  complete: false,
  failed: false
})

const toggleSelection = (buttonName: string) => {
  for (const key in buttonStates) {
    const button = key === buttonName
    if (button) {
      searchData.buttonType = buttonName
      resetEnterTime()
      getTableData()
    }
    buttonStates[key] = button
  }
}
const States = ref(false)
const closes = () => {
  States.value = !States.value
}

const handleDetails = (row: any) => {
  console.log("handleDetails")
  if (detailsRef.value) {
    detailsRef.value.dialogShow(row)
  }
}
const handleCreates = (row: any) => {
  if (createRef.value) {
    createRef.value.dialogShow(row)
  }
}

const handleUploadImage = (row: any) => {
  if (row.company_id == 0) {
    ElMessage.warning("请先添加客户")
    return
  }
  if (ImageRecognitionUploaderRef.value) {
    ImageRecognitionUploaderRef.value.openUploadDialog(
      row.company_name,
      row.company_id,
      row.admin_id,
      searchData.buttonType
    )
  }
}

const handleImportImage = () => {
  if (ImageRecognitionImporterRef.value) {
    ImageRecognitionImporterRef.value.openUploadDialog()
  }
}
const handleUpload = () => {
  if (UploadDialogRef.value) {
    UploadDialogRef.value.dialogShow()
  }
}

const handleUploadAdd = (row: any) => {
  handleCreates(row)
}
const handleInput = (event: any) => {
  event = event.replace(/，/g, ",")
  searchData.acceptorName = event.replace(/\s+/g, ",")
}

const handleBatchEdit = () => {
  if (Object.keys(lists).length === 0) {
    ElMessage.warning("请选择需要操作的票据")
    return
  }
  console.log("handleBatchEdit")
  console.log(JSON.stringify(Object.values(lists)))
  if (batchEditRef.value) {
    batchEditRef.value.showClick(lists)
  }
}

const handleBatchDelete = () => {
  if (Object.keys(lists).length === 0) {
    ElMessage.warning("请选择需要操作的票据")
    return
  }
  ElMessageBox.confirm("是否确认要删除选中的票据?", "票据删除", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const selectedFields = Object.values(lists).map((value: any) => value.bill_id)
      batchDeleteApi({
        billIds: selectedFields
      }).then(() => {
        ElMessage.success("删除成功")
        getTableData()
      })
    })
    .catch(() => {})
}

// #region 修改票面背书人
const doEditBillBackUser = (el: any) => {
  ElMessageBox.prompt("请输入背书人信息", "修改背书人", {
    confirmButtonText: "确认",
    cancelButtonText: "取消"
  })
    .then(({ value }) => {
      const data = {
        bill_id: el.bill_id,
        bill_back_user: value
      }
      doEditBillBackUserApi(data).then(() => {
        ElMessage.success("修改成功")
        getTableData()
      })
    })
    .catch(() => {})
}
// #endregion

// #region 票面信息
const faceShow = (el: any) => {
  if (faceRef.value) {
    faceRef.value.dialogShow(el)
  }
}
// #endregion

// #region 恢复
const doCancel = (el: any) => {
  doCancelApi({
    bill_id: el.bill_id
  }).then(() => {
    ElMessage.success("操作成功")
    getTableData()
  })
}
// #endregion

// #region 公司类型
const invoicingList = ref<any[]>([])
const INVOICINGFun = async () => {
  const res = await dictDataGetList("COMPANY_INVOICING")
  invoicingList.value = res.data
}
const checkList = ref<any[]>([])
const checkFun = async () => {
  const res = await dictDataGetList("COMPANY_CHECK")
  checkList.value = res.data
}

const dictDataGetList = async (type: string) => {
  try {
    const res = await dictDataGetListApi({ type_code: type })
    return res
  } catch (error) {
    console.error("Error:", error)
  }
}
INVOICINGFun()
checkFun()
// #endregion

import zgbank from "@/assets/bill/bank/zgbank.png"
import zxbank from "@/assets/bill/bank/zxbank.png"
import tzbank from "@/assets/bill/bank/tzbank.png"
import nybank from "@/assets/bill/bank/nybank.png"
import ylbank from "@/assets/bill/bank/ylbank.png"
import gsbank from "@/assets/bill/bank/gsbank.png"
const imgsList: { [key: string]: string } = {
  中国银行: zgbank,
  中信银行: zxbank,
  台州银行: tzbank,
  农业银行: nybank,
  亿联银行: ylbank,
  工商银行: gsbank
}

const third_party_userList: { [key: number]: string } = {
  20001848: "郑秀",
  20001850: "欣颖",
  20001853: "杨慧"
}

// const formatText = (text: string) => {
//   // 判断如果为null 则返回空字符串
//   if (text === null) {
//     return ""
//   }
//   return text
// }
const formatIds = (third_party_user_id: number) => {
  if (third_party_user_id == null) {
    return ""
  }
  const third_party_user = third_party_userList[third_party_user_id] ?? "其他"
  return third_party_user
}

//#region
const shouldShowButton = (enterNickname: string, enterCompanyId: number) => {
  const excludedIds = [2, 22, 31, 28]
  return enterNickname !== "" && !excludedIds.includes(enterCompanyId)
}
const handleHistorys = (row: any) => {
  console.log("handleHistorys")
  console.log(row)
  if (row.enter_company_id == "" || row.enter_company_id == null) {
    ElMessage.error("当前公司未添加或是新添加，请稍后再试")
    return
  }
  if (HistoryRef.value) {
    HistoryRef.value.dialogShow(row)
  }
}
//#endregion

// #region 结账
const handleCheckout = (row: any) => {
  if (checkoutRef.value) {
    checkoutRef.value?.dialogShow(row)
  }
}
// #endregion

// #region 回撤列表查询
const handleCatchList = () => {
  if (CatchListDialogRef.value) {
    CatchListDialogRef.value.openDialog()
  }
}

const handleCatchConfirm = (selectedData: any[]) => {
  console.log("确认选择的数据:", selectedData)
  ElMessage.success(`已确认选择 ${selectedData.length} 条数据`)
  // 这里可以添加具体的回撤逻辑
}

const handleCatchView = (row: any) => {
  console.log("查看数据:", row)
  // 这里可以添加查看详情的逻辑
}

const handleCatchEdit = (row: any) => {
  console.log("编辑数据:", row)
  // 这里可以添加编辑的逻辑
}

const handleCatchBatchOperation = (selectedData: any[]) => {
  console.log("批量操作数据:", selectedData)
  ElMessage.success(`批量操作 ${selectedData.length} 条数据`)
  // 这里可以添加批量操作的逻辑
}
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="hover" class="search-wrapper">
      <div style="margin-bottom: 20px">
        <el-row class="row-bg" justify="space-between">
          <el-col :span="6"
            ><el-space :size="30">
              <template v-for="item in buttonList" :key="item.name">
                <el-badge :value="item.badge" class="item">
                  <el-button
                    :type="buttonStates[item.name] ? 'primary' : 'default'"
                    @click="toggleSelection(item.name)"
                  >
                    {{ item.label }}
                  </el-button>
                </el-badge>
              </template>
            </el-space>
          </el-col>
          <el-col :span="12"
            ><el-row>
              <el-col :span="6">
                <div>
                  <div class="title">票据总数</div>
                  <div class="content">{{ countData.enter_count }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div>
                  <div class="title">票面金额（万元）</div>
                  <div class="content">{{ countData.enter_amount }}</div>
                </div>
              </el-col>
              <el-col :span="6" v-if="searchData.buttonType == 'complete'">
                <div>
                  <div class="title">实付金额（元）</div>
                  <div class="content">{{ countData.enter_complete }}</div>
                </div>
              </el-col>
              <el-col :span="6" v-if="searchData.buttonType == 'complete'">
                <div>
                  <div class="title">贴息费（元）</div>
                  <div class="content">{{ countData.enter_discount }}</div>
                </div>
              </el-col>
            </el-row></el-col
          >
        </el-row>
        <el-divider />
        <el-row class="row-bg" justify="space-between">
          <el-col :span="24">
            <el-form ref="searchFormRef" :inline="true" :model="searchData">
              <el-form-item label="票号">
                <el-input v-model="searchData.billNo" placeholder="请输入" clearable />
              </el-form-item>
              <el-form-item label="承兑人">
                <el-input v-model="searchData.acceptorName" placeholder="请输入" clearable @input="handleInput" />
              </el-form-item>
              <el-form-item label="背书人">
                <el-input v-model="searchData.bill_back_user" placeholder="请输入" clearable />
              </el-form-item>

              <el-form-item label="票面金额" v-if="States">
                <el-col :span="11">
                  <el-input v-model="searchData.billAmountMin" placeholder="请输入" clearable />
                </el-col>
                <el-col :span="2" class="text-center">
                  <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                  <el-input v-model="searchData.billAmountMax" placeholder="请输入" clearable />
                </el-col>
              </el-form-item>
              <el-form-item label="业务员" v-if="States">
                <el-select v-model="searchData.uid" placeholder="请选择" clearable>
                  <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="客户类别" v-if="States">
                <el-select v-model="searchData.company_type" placeholder="请选择" clearable>
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="入库时间" v-if="States && searchData.buttonType != 'incomplete'">
                <el-col :span="11">
                  <el-date-picker
                    clearable
                    :format="customDateTimeFormat"
                    :value-format="customDateTimeFormat"
                    v-model="searchData.enter_timeStart"
                    type="datetime"
                    placeholder="请选择"
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="2" class="text-center">
                  <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                  <el-date-picker
                    clearable
                    :format="customDateTimeFormat"
                    :value-format="customDateTimeFormat"
                    v-model="searchData.enter_timeEnd"
                    type="datetime"
                    placeholder="请选择"
                    style="width: 100%"
                  />
                </el-col>
              </el-form-item>
              <el-form-item label="到期日" v-if="States">
                <el-col :span="11">
                  <el-date-picker
                    clearable
                    :format="customDateFormat"
                    :value-format="customDateFormat"
                    v-model="searchData.expirationDateStart"
                    type="date"
                    placeholder="请选择"
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="2" class="text-center">
                  <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                  <el-date-picker
                    clearable
                    :format="customDateFormat"
                    :value-format="customDateFormat"
                    v-model="searchData.expirationDateEnd"
                    type="date"
                    placeholder="请选择"
                    style="width: 100%"
                  />
                </el-col>
              </el-form-item>
              <el-form-item label="识别日期" v-if="States">
                <el-col :span="11">
                  <el-date-picker
                    clearable
                    :format="customDateTimeFormat"
                    :value-format="customDateTimeFormat"
                    v-model="searchData.date1"
                    type="datetime"
                    placeholder="请选择"
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="2" class="text-center">
                  <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                  <el-date-picker
                    clearable
                    :format="customDateTimeFormat"
                    :value-format="customDateTimeFormat"
                    v-model="searchData.date2"
                    type="datetime"
                    placeholder="请选择"
                    style="width: 100%"
                  />
                </el-col>
              </el-form-item>
              <el-form-item label="是否开票" prop="invoicing_type" v-if="States">
                <el-select v-model="searchData.invoicing_type" placeholder="请选择" clearable>
                  <el-option
                    v-for="item in invoicingList"
                    :key="item.data_value"
                    :label="item.data_name"
                    :value="item.data_value"
                  />
                </el-select>
                <!-- <el-radio-group v-model="searchData.invoicing_type">
                  <el-radio :value="0">全部</el-radio>
                  <el-radio v-for="option in invoicingList" :key="option.data_value" :label="Number(option.data_value)">
                    {{ option.data_name }}
                  </el-radio>
                </el-radio-group> -->
              </el-form-item>
              <el-form-item label="先款先票" prop="check_type" v-if="States">
                <el-select v-model="searchData.check_type" placeholder="请选择" clearable>
                  <el-option
                    v-for="item in checkList"
                    :key="item.data_value"
                    :label="item.data_name"
                    :value="item.data_value"
                  />
                </el-select>
                <!-- <el-radio-group v-model="searchData.check_type">
                  <el-radio :value="0">全部</el-radio>
                  <el-radio v-for="option in checkList" :key="option.data_value" :label="Number(option.data_value)">
                    {{ option.data_name }}
                  </el-radio>
                </el-radio-group> -->
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
                <el-button @click="closes">{{ States ? "收起" : "展开" }}</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <el-card v-loading="loading" shadow="hover" class="search-wrapper">
      <div style="margin-bottom: 20px">
        <el-row>
          <el-col :span="20">
            <div style="height: 20px; display: flex; align-items: center">
              <el-icon v-if="countBool" style="margin-right: 10px"><Warning /></el-icon>
              <span v-if="countBool">
                共<span style="color: red">{{ selectedCountData.count }}</span
                >张票据
              </span>
              <span v-if="countBool">
                ，票面总金额<span style="color: red">{{ selectedCountData.amount }}</span
                >万元
              </span>
              <template v-if="countBool"
                ><span v-if="searchData.buttonType == 'complete'">
                  ，实付金额<span style="color: red">{{ selectedCountData.complete }}</span
                  >元
                </span>
                <span v-if="searchData.buttonType == 'complete'">
                  ，贴息费<span style="color: red">{{ selectedCountData.discount }}</span
                  >元
                </span></template
              >
            </div>
          </el-col>
          <el-col :span="4">
            <div style="display: flex; justify-content: flex-end">
              <el-tooltip content="导出">
                <el-button type="primary" :icon="Download" circle @click="getBillExport2" />
              </el-tooltip>
            </div>
          </el-col>
          <!--          <el-col :span="6" style="display: flex; justify-content: flex-end">-->
          <!--            <el-button type="primary" plain @click="uploadLogShow">上传记录</el-button>-->
          <!--          </el-col>-->
        </el-row>
      </div>
    </el-card>

    <el-card v-loading="loading" shadow="hover">
      <div class="listbox">
        <div
          class="listbox-left"
          :style="{
            width: searchData.buttonType == 'pending' || searchData.buttonType == 'incomplete' ? '86%' : '100%'
          }"
          ref="listboxLeftRef"
        >
          <div class="toolbar-wrapper">
            <div>
              <el-button
                v-if="
                  searchData.buttonType != 'failed' &&
                  searchData.buttonType != 'complete' &&
                  searchData.buttonType != 'incomplete'
                "
                type="primary"
                :icon="CirclePlus"
                @click="dialogVisible = true"
              >
                新增
              </el-button>
              <el-button
                v-if="
                  searchData.buttonType != 'failed' &&
                  searchData.buttonType != 'complete' &&
                  searchData.buttonType != 'incomplete'
                "
                type="primary"
                :icon="UploadFilled"
                @click="handleImportImage()"
              >
                新增导入
              </el-button>
              <el-button
                v-if="
                  searchData.buttonType != 'failed' &&
                  searchData.buttonType != 'complete' &&
                  searchData.buttonType != 'incomplete'
                "
                type="primary"
                :icon="Tickets"
                @click="handBatchDialog"
              >
                批量入库
              </el-button>
              <el-button
                v-if="searchData.buttonType != 'failed' && searchData.buttonType != 'complete'"
                type="danger"
                :icon="Delete"
                @click="handleBatchDelete"
              >
                批量删除
              </el-button>
              <el-button
                v-if="searchData.buttonType == 'complete' || searchData.buttonType == 'incomplete'"
                type="primary"
                :icon="Tickets"
                @click="handleBatchEdit"
              >
                批量修改
              </el-button>
              <el-button
                v-if="searchData.buttonType == 'complete'"
                type="primary"
                :icon="Tickets"
                @click="handleUpload"
              >
                导入
              </el-button>
              <!-- <el-button
                v-if="
                  searchData.buttonType != 'failed' &&
                  searchData.buttonType != 'complete' &&
                  searchData.buttonType != 'incomplete'
                "
                type="primary"
                :icon="Tickets"
                @click="handleUploadImage"
              >
                识别
              </el-button> -->
              <el-button
                v-if="searchData.buttonType == 'complete' || searchData.buttonType == 'incomplete'"
                type="primary"
                :icon="Tickets"
                @click="handleCheckout"
              >
                结账
              </el-button>
              <el-button v-if="searchData.buttonType == 'pending'" type="primary" :icon="Tickets" @click="addCompany">
                添加企业
              </el-button>
              <el-button
                v-if="searchData.buttonType == 'complete' || searchData.buttonType == 'incomplete'"
                type="primary"
                :icon="Tickets"
                @click="handleCatchList"
              >
                回撤
              </el-button>
              <!--          <el-button type="danger" :icon="Delete">批量删除</el-button>-->
            </div>
            <div>
              <el-tooltip content="下载">
                <el-button type="primary" :icon="Download" circle @click="getBillExport" />
              </el-tooltip>
              <el-tooltip content="刷新当前页">
                <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
              </el-tooltip>
            </div>
          </div>
          <div class="table-wrapper">
            <el-table
              :data="tableData"
              :header-cell-style="{
                background: '#ecf4f9 !important',
                color: '#32617d !important',
                border: '1px solid #cccccc'
              }"
              class="ones"
              :row-style="rowStyle"
              :cell-style="modality"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              v-loading="tableLoading"
              border
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column prop="recognizerDate" label="识别日期" align="center" width="100" />
              <el-table-column prop="billNo" label="票号" width="100" align="center">
                <template #default="scope">
                  <div class="billNO2">
                    <span style="margin-left: 10px; cursor: pointer" @click="copyToClipboard(scope.row.billNo)">{{
                      scope.row.billNo
                    }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="acceptorName" label="承兑人" align="center">
                <template #default="{ row }">
                  <div>
                    <span class="face" @click="faceShow(row)">
                      <div class="face-title">{{ row.acceptorName }}</div>
                      <div class="face-item" v-if="row.bankName != null && row.third_party_user_id != null">
                        <img
                          style="width: 30px; height: 30px"
                          v-if="row.bankName != null"
                          :src="imgsList[row.bankName]"
                        />
                        <el-tag v-if="row.third_party_user_id != null">{{ formatIds(row.third_party_user_id) }}</el-tag>
                      </div>
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="billAmount" label="票面金额" align="center" width="100" />
              <el-table-column prop="expirationDate" label="到期日期" align="center" width="100" />
              <el-table-column label="入库" align="center" v-if="searchData.buttonType != 'pending'">
                <el-table-column prop="enter_time" width="100" label="时间" align="center" />
                <el-table-column prop="enter_price" label="每十万价格" align="center" width="100" />
                <el-table-column prop="enter_discount" label="贴息费" align="center" width="100" />
                <el-table-column prop="enter_finally" label="最终价格" align="center" width="100" />
              </el-table-column>
              <el-table-column prop="bill_back_user" label="背书人" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center; justify-content: center">
                    <el-tag v-if="scope.row.enter_invoicings == 1" style="margin-right: 10px">开票</el-tag>
                    <el-tag v-if="scope.row.enter_checks == 1" style="margin-right: 10px">先款先票</el-tag>
                    {{ scope.row.bill_back_user }}
                    <el-rate
                      v-if="scope.row.star_rating > 1"
                      v-model="scope.row.star_rating"
                      disabled
                      size="small"
                      :max="1"
                    />
                    <el-button
                      v-if="searchData.buttonType == 'pending' && scope.row.enter_nickname == ''"
                      type="primary"
                      text
                      bg
                      size="small"
                      @click="addCompany2(scope.row)"
                    >
                      添加
                    </el-button>
                    <el-button
                      v-if="searchData.buttonType == 'pending' && scope.row.bill_back_user_bool"
                      type="primary"
                      text
                      @click="doEditBillBackUser(scope.row)"
                    >
                      修改
                    </el-button>
                    <el-button
                      v-if="shouldShowButton(scope.row.enter_nickname, scope.row.enter_company_id)"
                      key="primary"
                      type="primary"
                      text
                      @click="handleHistorys(scope.row)"
                    >
                      详情
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="enter_nickname" label="业务员" align="center" width="100" />
              <el-table-column
                fixed="right"
                label="操作"
                width="150"
                align="center"
                v-if="searchData.buttonType != 'failed'"
              >
                <template #default="scope">
                  <el-button
                    v-if="searchData.buttonType == 'pending' && scope.row.enter_nickname != ''"
                    type="primary"
                    text
                    bg
                    size="small"
                    @click="handleUpdate(scope.row)"
                  >
                    入库
                  </el-button>
                  <el-button
                    v-if="
                      searchData.buttonType != 'pending' &&
                      searchData.buttonType != 'complete' &&
                      scope.row.enter_complete == 1
                    "
                    type="primary"
                    text
                    bg
                    size="small"
                    @click="handleEdits(scope.row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    v-if="searchData.buttonType == 'pending'"
                    type="danger"
                    text
                    bg
                    size="small"
                    @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                  <el-button
                    v-if="scope.row.enter_complete == 2"
                    type="primary"
                    text
                    bg
                    size="small"
                    @click="handleEdits(scope.row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    v-if="scope.row.enter_complete == 2"
                    type="info"
                    text
                    bg
                    size="small"
                    @click="handleDetails(scope.row)"
                  >
                    详情
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="80"
                align="center"
                v-if="searchData.buttonType == 'failed'"
              >
                <template #default="scope">
                  <el-button type="danger" text bg size="small" @click="doCancel(scope.row)"> 恢复 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pager-wrapper">
            <el-pagination
              background
              :layout="paginationData.layout"
              :page-sizes="paginationData.pageSizes"
              :total="paginationData.total"
              :page-size="paginationData.pageSize"
              :currentPage="paginationData.currentPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <div
          class="listbox-right"
          v-if="searchData.buttonType != 'failed' && searchData.buttonType != 'complete'"
          :style="{ height: height + 'px' }"
        >
          <div class="search-box">
            <el-input v-model="companySearchKeyword" placeholder="搜索公司名称" clearable prefix-icon="Search" />
          </div>
          <ul class="infinite-list">
            <li v-for="i in filteredPendingCompanies" :key="i" class="infinite-list-item" @click="handleUploadImage(i)">
              {{ i.company_name }}
            </li>
          </ul>
        </div>
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="billNo" label="票号">
          <el-input v-model="formData.billNo" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="billAmount" label="金额(万)">
          <el-input v-model="formData.billAmount" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="expirationDate" label="到期日">
          <el-date-picker
            :format="customDateFormat"
            :value-format="customDateFormat"
            v-model="formData.expirationDate"
            type="date"
            placeholder="请选择"
            style="width: 100%"
          />
          <!-- <el-input v-model="formData.expirationDate" placeholder="请输入" /> -->
        </el-form-item>
        <el-form-item prop="acceptorName" label="承兑人">
          <el-input v-model="formData.acceptorName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="bill_back_user" label="背书人">
          <el-input v-model="formData.bill_back_user" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <!-- <el-button @click="dialogVisible = false">取消</el-button> -->
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <Warehouse ref="dialogRef" @dialog-close="handleSearch" />
    <edit ref="editRef" @dialog-close="handleSearch" />
    <batch ref="batchRef" @batch-close="handleSearch" />
    <getDetails ref="detailsRef" @details-close="handleSearch" />
    <UploadDialog ref="UploadDialogRef" @upload-close="handleUploadAdd" />
    <ImageRecognitionUploader ref="ImageRecognitionUploaderRef" @upload-close="handleSearch" />
    <ImageRecognitionImporter ref="ImageRecognitionImporterRef" @upload-close="handleSearch" />
    <Create ref="createRef" @create-close="handleSearch" />
    <price ref="priceRef" @batch-close="handleSearch" />
    <uploadLog ref="uploadLogRef" @uploadLog-close="handleSearch" />
    <batch-edit ref="batchEditRef" @dialog-close="handleSearch" />
    <checkout ref="checkoutRef" @dialog-close="handleSearch" />
    <face ref="faceRef" />
    <History ref="HistoryRef" />
    <Retreat
      ref="CatchListDialogRef"
      @confirm="handleCatchConfirm"
      @view="handleCatchView"
      @edit="handleCatchEdit"
      @batch-operation="handleCatchBatchOperation"
    />
  </div>
</template>

<style lang="scss" scoped>
.ones {
  background: #f4f8fb;
  border: 1px solid #cccccc;
}

.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.title {
  line-height: 20px;
  margin-bottom: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #606266;
}
.content {
  font-size: 20px;
  font-weight: 400;
  color: #303133;
}
.billNO {
  display: flex;
  align-items: center;
  color: #2e90f7;
}
.billNO2 {
  display: flex;
  align-items: center;
}
.face {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #2e90f7;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
  img {
    margin: 10px;
  }
  .face-title {
    display: flex;
    align-items: center;
    color: #2e90f7;
    justify-content: center;
    flex-wrap: wrap;
    width: 80%;
  }
  .face-item {
    display: flex;
    align-items: center;
    color: #2e90f7;
    justify-content: center;
    width: 20%;
  }
}
// .face img {
//   margin: 10px;
// }
.listbox {
  display: flex;
  justify-content: space-between;
  .listbox-left {
    width: 86%;
  }
  .listbox-right {
    width: 200px;
    border-left: 1px solid #eee;
    overflow-y: auto;
  }
  .search-box {
    padding: 10px;
    border-bottom: 1px solid #eee;
  }
  .infinite-list {
    padding: 0;
    margin: 0;
    list-style: none;
  }
  .infinite-list-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    padding: 10px;
    margin: 10px;
    border-bottom: 1px solid #f0f0f0;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
    cursor: pointer;
    font-size: 14px;
    transition: background-color 0.3s;
  }
  .infinite-list-item:hover {
    background-color: #f5f7fa;
  }
}

.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}
</style>
